<template>
  <div class="school-calendar-container">
    <div class="header">
      <h2>校历与地图管理</h2>
    </div>

    <!-- 标签页 -->
    <el-tabs v-model="activeTab" type="card">
      <!-- 校历管理标签页 -->
      <el-tab-pane label="校历管理" name="calendar">
        <div class="tab-content">
          <div class="actions">
            <el-button type="primary" @click="showSyncDialog">从远程同步</el-button>
          </div>

          <el-table :data="calendars" style="width: 100%" v-loading="loading">
            <el-table-column prop="school_title" label="校历标题" width="300"></el-table-column>
            <el-table-column prop="updated_at" label="更新时间" width="200">
              <template #default="scope">
                {{ formatDate(scope.row.updated_at) }}
              </template>
            </el-table-column>
            <el-table-column label="操作">
              <template #default="scope">
                <el-button type="primary" size="small" @click="previewCalendar(scope.row)">预览</el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </el-tab-pane>

      <!-- 校园地图编辑标签页 -->
      <el-tab-pane label="校园地图编辑" name="campus-map">
        <div class="tab-content">
          <div class="campus-map-container">
            <!-- 广州校区 -->
            <div class="campus-section">
              <h3>广州校区地图</h3>
              <div class="image-preview">
                <img :src="gzxqImageUrl" alt="广州校区地图" @error="handleImageError" class="campus-image" />
              </div>
              <div class="upload-section">
                <el-upload
                  :action="null"
                  :auto-upload="false"
                  :show-file-list="false"
                  accept="image/*"
                  :before-upload="validateFile"
                  @change="handleGzxqUpload"
                >
                  <el-button type="primary" :disabled="gzxqUploading">上传新图片</el-button>
                </el-upload>
                <el-button type="success" @click="refreshGzxqImage" :loading="gzxqLoading"> 刷新预览 </el-button>
              </div>

              <!-- 广州校区上传进度 -->
              <div v-if="gzxqUploading" class="upload-progress">
                <el-progress
                  :percentage="gzxqProgress"
                  :status="gzxqProgress === 100 ? 'success' : ''"
                  :stroke-width="8"
                />
                <div class="progress-text">
                  {{ gzxqProgress === 100 ? "上传完成" : `上传中 ${gzxqProgress}%` }}
                </div>
              </div>

              <!-- 广州校区上传状态 -->
              <div v-if="gzxqUploadStatus" class="upload-status" :class="gzxqUploadStatus.type">
                <el-icon v-if="gzxqUploadStatus.type === 'success'"><CircleCheck /></el-icon>
                <el-icon v-else-if="gzxqUploadStatus.type === 'error'"><CircleClose /></el-icon>
                <span>{{ gzxqUploadStatus.message }}</span>
                <el-button v-if="gzxqUploadStatus.type === 'error'" type="text" size="small" @click="retryGzxqUpload">
                  重试
                </el-button>
              </div>
            </div>

            <!-- 江门校区 -->
            <div class="campus-section">
              <h3>江门校区地图</h3>
              <div class="image-preview">
                <img :src="jmxqImageUrl" alt="江门校区地图" @error="handleImageError" class="campus-image" />
              </div>
              <div class="upload-section">
                <el-upload
                  :action="null"
                  :auto-upload="false"
                  :show-file-list="false"
                  accept="image/*"
                  :before-upload="validateFile"
                  @change="handleJmxqUpload"
                >
                  <el-button type="primary" :disabled="jmxqUploading">上传新图片</el-button>
                </el-upload>
                <el-button type="success" @click="refreshJmxqImage" :loading="jmxqLoading"> 刷新预览 </el-button>
              </div>

              <!-- 江门校区上传进度 -->
              <div v-if="jmxqUploading" class="upload-progress">
                <el-progress
                  :percentage="jmxqProgress"
                  :status="jmxqProgress === 100 ? 'success' : ''"
                  :stroke-width="8"
                />
                <div class="progress-text">
                  {{ jmxqProgress === 100 ? "上传完成" : `上传中 ${jmxqProgress}%` }}
                </div>
              </div>

              <!-- 江门校区上传状态 -->
              <div v-if="jmxqUploadStatus" class="upload-status" :class="jmxqUploadStatus.type">
                <el-icon v-if="jmxqUploadStatus.type === 'success'"><CircleCheck /></el-icon>
                <el-icon v-else-if="jmxqUploadStatus.type === 'error'"><CircleClose /></el-icon>
                <span>{{ jmxqUploadStatus.message }}</span>
                <el-button v-if="jmxqUploadStatus.type === 'error'" type="text" size="small" @click="retryJmxqUpload">
                  重试
                </el-button>
              </div>
            </div>
          </div>
        </div>
      </el-tab-pane>
    </el-tabs>

    <!-- 预览对话框 -->
    <el-dialog title="校历预览" v-model="previewVisible" width="80%">
      <div class="preview-container" v-html="previewContent"></div>
    </el-dialog>

    <!-- 同步对话框 -->
    <el-dialog title="从远程同步校历" v-model="syncDialogVisible" width="50%">
      <el-form :model="syncForm" ref="syncFormRef" label-width="120px">
        <el-form-item
          label="授权令牌"
          prop="token"
          :rules="[{ required: true, message: '请输入授权令牌', trigger: 'blur' }]"
        >
          <el-input v-model="syncForm.token" type="textarea" :rows="4" placeholder="请输入Bearer Token"> </el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="syncDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="syncCalendars" :loading="syncLoading">同步</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script>
  import { ref, onMounted, reactive } from "vue";
  import { ElMessage, ElMessageBox } from "element-plus";
  import { CircleCheck, CircleClose } from "@element-plus/icons-vue";
  import api from "../axios/api";

  export default {
    name: "SchoolCalendarList",
    components: {
      CircleCheck,
      CircleClose
    },
    setup() {
      const activeTab = ref("calendar");
      const loading = ref(false);
      const previewVisible = ref(false);
      const syncDialogVisible = ref(false);
      const syncLoading = ref(false);
      const calendars = ref([]);
      const previewContent = ref("");
      const syncFormRef = ref(null);

      // 校园地图相关状态
      const gzxqLoading = ref(false);
      const jmxqLoading = ref(false);
      const gzxqImageUrl = ref(
        `${import.meta.env.VITE_API_BASE_URL}/manual_html/public/images/gzxq.jpg?t=${Date.now()}`
      );
      const jmxqImageUrl = ref(
        `${import.meta.env.VITE_API_BASE_URL}/manual_html/public/images/jmxq.jpg?t=${Date.now()}`
      );

      // 上传相关状态
      const gzxqUploading = ref(false);
      const jmxqUploading = ref(false);
      const gzxqProgress = ref(0);
      const jmxqProgress = ref(0);
      const gzxqUploadStatus = ref(null);
      const jmxqUploadStatus = ref(null);
      const gzxqLastFile = ref(null);
      const jmxqLastFile = ref(null);

      const syncForm = reactive({
        token: ""
      });

      // 文件验证函数
      const validateFile = file => {
        // 检查文件大小 (10MB = 10 * 1024 * 1024 bytes)
        const maxSize = 10 * 1024 * 1024;
        if (file.size > maxSize) {
          ElMessage.error(`文件大小不能超过10MB，当前文件大小: ${(file.size / 1024 / 1024).toFixed(2)}MB`);
          return false;
        }

        // 检查文件类型
        const allowedTypes = ["image/jpeg", "image/jpg", "image/png", "image/gif", "image/webp"];
        if (!allowedTypes.includes(file.type)) {
          ElMessage.error("只支持 JPG、PNG、GIF、WebP 格式的图片");
          return false;
        }

        return true;
      };

      // 获取所有校历
      const fetchCalendars = async () => {
        loading.value = true;
        try {
          const response = await api.getAllSchoolCalendars();
          calendars.value = response.data;
        } catch (error) {
          console.error("获取校历失败:", error);
          ElMessage.error("获取校历失败");
        } finally {
          loading.value = false;
        }
      };

      // 格式化日期
      const formatDate = dateString => {
        const date = new Date(dateString);
        return date.toLocaleString();
      };

      // 预览校历
      const previewCalendar = row => {
        previewContent.value = row.calendar_content;
        previewVisible.value = true;
      };

      // 显示同步对话框
      const showSyncDialog = () => {
        syncForm.token = "";
        syncDialogVisible.value = true;
      };

      // 同步校历
      const syncCalendars = async () => {
        if (!syncFormRef.value) return;

        await syncFormRef.value.validate(async valid => {
          if (!valid) return;

          syncLoading.value = true;
          try {
            const token = syncForm.token.trim();
            const response = await api.syncSchoolCalendarsFromRemote(token);

            ElMessage.success("同步校历成功");
            console.log("同步结果:", response.data);
            syncDialogVisible.value = false;
            fetchCalendars();
          } catch (error) {
            console.error("同步校历失败:", error);
            ElMessage.error(error.response?.data?.detail || "同步校历失败");
          } finally {
            syncLoading.value = false;
          }
        });
      };

      // 处理图片加载错误
      const handleImageError = event => {
        event.target.src =
          "";
      };

      // 刷新广州校区图片
      const refreshGzxqImage = () => {
        gzxqLoading.value = true;
        const timestamp = Date.now();
        gzxqImageUrl.value = `${import.meta.env.VITE_API_BASE_URL}/manual_html/public/images/gzxq.jpg?t=${timestamp}`;
        setTimeout(() => {
          gzxqLoading.value = false;
        }, 1000);
      };

      // 刷新江门校区图片
      const refreshJmxqImage = () => {
        jmxqLoading.value = true;
        const timestamp = Date.now();
        jmxqImageUrl.value = `${import.meta.env.VITE_API_BASE_URL}/manual_html/public/images/jmxq.jpg?t=${timestamp}`;
        setTimeout(() => {
          jmxqLoading.value = false;
        }, 1000);
      };

      // 处理广州校区图片上传
      const handleGzxqUpload = async file => {
        if (!file.raw) return;

        gzxqLastFile.value = file.raw;
        gzxqUploading.value = true;
        gzxqProgress.value = 0;
        gzxqUploadStatus.value = null;

        try {
          const response = await api.uploadCampusMapImage("gzxq", file.raw, progressEvent => {
            if (progressEvent.total) {
              gzxqProgress.value = Math.round((progressEvent.loaded * 100) / progressEvent.total);
            }
          });

          gzxqProgress.value = 100;
          gzxqUploadStatus.value = {
            type: "success",
            message: "广州校区地图上传成功"
          };

          ElMessage.success("广州校区地图上传成功");
          // 上传成功后立即刷新图片，添加时间戳防止缓存
          const timestamp = Date.now();
          gzxqImageUrl.value = `${import.meta.env.VITE_API_BASE_URL}/manual_html/public/images/gzxq.jpg?t=${timestamp}`;

          // 3秒后清除状态
          setTimeout(() => {
            gzxqUploadStatus.value = null;
          }, 3000);
        } catch (error) {
          console.error("上传广州校区地图失败:", error);
          gzxqUploadStatus.value = {
            type: "error",
            message: error.response?.data?.detail || "上传失败，请重试"
          };
          ElMessage.error(error.response?.data?.detail || "上传失败");
        } finally {
          gzxqUploading.value = false;
        }
      };

      // 处理江门校区图片上传
      const handleJmxqUpload = async file => {
        if (!file.raw) return;

        jmxqLastFile.value = file.raw;
        jmxqUploading.value = true;
        jmxqProgress.value = 0;
        jmxqUploadStatus.value = null;

        try {
          const response = await api.uploadCampusMapImage("jmxq", file.raw, progressEvent => {
            if (progressEvent.total) {
              jmxqProgress.value = Math.round((progressEvent.loaded * 100) / progressEvent.total);
            }
          });

          jmxqProgress.value = 100;
          jmxqUploadStatus.value = {
            type: "success",
            message: "江门校区地图上传成功"
          };

          ElMessage.success("江门校区地图上传成功");
          // 上传成功后立即刷新图片，添加时间戳防止缓存
          const timestamp = Date.now();
          jmxqImageUrl.value = `${import.meta.env.VITE_API_BASE_URL}/manual_html/public/images/jmxq.jpg?t=${timestamp}`;

          // 3秒后清除状态
          setTimeout(() => {
            jmxqUploadStatus.value = null;
          }, 3000);
        } catch (error) {
          console.error("上传江门校区地图失败:", error);
          jmxqUploadStatus.value = {
            type: "error",
            message: error.response?.data?.detail || "上传失败，请重试"
          };
          ElMessage.error(error.response?.data?.detail || "上传失败");
        } finally {
          jmxqUploading.value = false;
        }
      };

      // 重试广州校区上传
      const retryGzxqUpload = () => {
        if (gzxqLastFile.value) {
          handleGzxqUpload({ raw: gzxqLastFile.value });
        }
      };

      // 重试江门校区上传
      const retryJmxqUpload = () => {
        if (jmxqLastFile.value) {
          handleJmxqUpload({ raw: jmxqLastFile.value });
        }
      };

      onMounted(() => {
        fetchCalendars();
      });

      return {
        activeTab,
        loading,
        calendars,
        previewVisible,
        syncDialogVisible,
        previewContent,
        syncForm,
        syncLoading,
        syncFormRef,
        gzxqLoading,
        jmxqLoading,
        gzxqImageUrl,
        jmxqImageUrl,
        gzxqUploading,
        jmxqUploading,
        gzxqProgress,
        jmxqProgress,
        gzxqUploadStatus,
        jmxqUploadStatus,
        fetchCalendars,
        formatDate,
        previewCalendar,
        showSyncDialog,
        syncCalendars,
        handleImageError,
        refreshGzxqImage,
        refreshJmxqImage,
        handleGzxqUpload,
        handleJmxqUpload,
        validateFile,
        retryGzxqUpload,
        retryJmxqUpload
      };
    }
  };
</script>

<style scoped>
  .school-calendar-container {
    padding: 20px;
  }

  .header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
  }

  .tab-content {
    padding: 20px 0;
  }

  .actions {
    display: flex;
    gap: 10px;
    margin-bottom: 20px;
  }

  .preview-container {
    border: 1px solid #dcdfe6;
    border-radius: 4px;
    padding: 15px;
    min-height: 200px;
    max-height: 500px;
    overflow: auto;
    background-color: #fff;
  }

  .campus-map-container {
    display: flex;
    gap: 40px;
    justify-content: space-between;
  }

  .campus-section {
    flex: 1;
    display: flex;
    flex-direction: column;
    align-items: center;
  }

  .campus-section h3 {
    margin-bottom: 20px;
    color: #303133;
  }

  .image-preview {
    width: 100%;
    max-width: 400px;
    height: 300px;
    border: 2px dashed #dcdfe6;
    border-radius: 8px;
    display: flex;
    align-items: center;
    justify-content: center;
    margin-bottom: 20px;
    background-color: #fafafa;
    overflow: hidden;
  }

  .campus-image {
    max-width: 100%;
    max-height: 100%;
    object-fit: contain;
  }

  .upload-section {
    display: flex;
    gap: 10px;
    flex-wrap: wrap;
    justify-content: center;
    margin-bottom: 15px;
  }

  .upload-progress {
    width: 100%;
    max-width: 400px;
    margin-bottom: 15px;
  }

  .progress-text {
    text-align: center;
    margin-top: 8px;
    font-size: 14px;
    color: #606266;
  }

  .upload-status {
    display: flex;
    align-items: center;
    gap: 8px;
    padding: 8px 12px;
    border-radius: 6px;
    font-size: 14px;
    margin-bottom: 15px;
    max-width: 400px;
    width: 100%;
  }

  .upload-status.success {
    background-color: #f0f9ff;
    color: #67c23a;
    border: 1px solid #b3e19d;
  }

  .upload-status.error {
    background-color: #fef0f0;
    color: #f56c6c;
    border: 1px solid #fab6b6;
  }

  .upload-status .el-button {
    margin-left: auto;
    color: #f56c6c;
  }

  .upload-status .el-button:hover {
    color: #f78989;
  }

  /* 响应式设计 */
  @media (max-width: 768px) {
    .campus-map-container {
      flex-direction: column;
      gap: 20px;
    }

    .campus-section {
      width: 100%;
    }
  }
</style>
